package com.xhh.nphm.gaoxin.controller;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xhh.nphm.common.core.controller.BaseController;
import com.xhh.nphm.common.core.domain.AjaxResult;
import com.xhh.nphm.common.core.domain.QueryConditionVo;
import com.xhh.nphm.common.core.domain.entity.SysUser;
import com.xhh.nphm.common.core.page.TableDataInfo;
import com.xhh.nphm.common.utils.DateUtils;
import com.xhh.nphm.common.utils.ShiroUtils;
import com.xhh.nphm.common.utils.StringUtils;
import com.xhh.nphm.gaoxin.entity.GxqTwfSendBackEty;
import com.xhh.nphm.gaoxin.entity.GxqTworkFormBaseEty;
import com.xhh.nphm.gaoxin.entity.GxqTworkFormLogEty;
import com.xhh.nphm.gaoxin.service.GxqITworkFormLogService;
import com.xhh.nphm.gaoxin.service.GxqIWfSendBackService;
import com.xhh.nphm.gaoxin.service.GxqIWorkFormBaseService;
import com.xhh.nphm.system.mapper.CommonDao;
import com.xhh.nphm.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/gaoxin/system/mTelWF/rCity")
public class GxqMTelWFrCityController extends BaseController {
    private final String prefix = "system/gaoxin/mTelWF/rCity";
    @Autowired
    private CommonDao commonDao;
    @Autowired
    private ITagService tagService;
    @Autowired
    private ISmsNoteService smsNoteService;
    @Autowired
    private IReplyTemplateService replyTemplateService;

    @Autowired
    private GxqIWfSendBackService gxqWfSendBackService;
    @Autowired
    private GxqIWorkFormBaseService gxqWorkFormBaseService;
    @Autowired
    private GxqITworkFormLogService gxqITworkFormLogService;

    /**
     * 进入待分发下级列表页面
     */
    @GetMapping("/sendWaitList")
    public ModelAndView sendWaitList() {
        return new ModelAndView(prefix + "/sendWaitList");
    }

    /**
     * 加载待分发下级列表数据
     */
    @PostMapping("/sendWaitListJson")
    public TableDataInfo sendWaitListJson(@RequestParam("workFormNo") String workFormNo, @RequestParam("sdeptName") String sdeptName) {
        startPage();
        SysUser user = ShiroUtils.getSysUser();
        List<Map<String, Object>> list;
        if (IS_GAOXIN()){
            list = gxqWfSendBackService.sendWaitListJson_gxq(user.getDeptId(), workFormNo, sdeptName);
        }else{
            list = gxqWfSendBackService.sendWaitListJson(user.getDeptId(), workFormNo, sdeptName);
        }
        return getDataTable(list);
    }

    /**
     * 进入下级退回T列表页面
     */
    @GetMapping("/listSonBack")
    public ModelAndView listSonBack() {
        return new ModelAndView(prefix + "/listSonBack");
    }

    /**
     * 加载下级退回T列表数据
     */
    @PostMapping("/listSonBackJson")
    public TableDataInfo listSonBackJson(@RequestParam("workFormNo") String workFormNo, @RequestParam("sdeptName") String sdeptName) {
        startPage();
        SysUser user = ShiroUtils.getSysUser();
        List<Map<String, Object>> list = gxqWfSendBackService.listSonBackJson(user.getDeptId(), workFormNo, sdeptName);
        return getDataTable(list);
    }


    /**
     * 进入下级退回待处理T列表页面
     */
    @GetMapping("/listSonNABack")
    public ModelAndView listSonNABack(ModelMap map) {
        SysUser user = getSysUser();
        map.put("smsInform",smsNoteService.selectSmsInform(user.getDeptId().toString(),user.getUserId().toString()));
        return new ModelAndView(prefix + "/listSonNABack");
    }

    /**
     * 加载下级退回待处理T列表数据
     */
    @PostMapping("/listSonNABackJson")
    public TableDataInfo listSonNABackJson(@RequestParam("workFormNo") String workFormNo, @RequestParam("sdeptName") String sdeptName) {
        startPage();
        SysUser user = ShiroUtils.getSysUser();
        List<Map<String, Object>> list;
        if (IS_GAOXIN()){
            list = gxqWfSendBackService.listSonNABackJson_gxq(user.getDeptId(), workFormNo, sdeptName);
        }else{
            list = gxqWfSendBackService.listSonNABackJson(user.getDeptId(), workFormNo, sdeptName);
        }
        return getDataTable(list);
    }

    /**
     * 进入下级退回已处理T列表页面
     */
    @GetMapping("/listSonABack")
    public ModelAndView listSonABack() {
        return new ModelAndView(prefix + "/listSonABack");
    }

    /**
     * 加载下级退回已处理T列表数据
     */
    @PostMapping("/listSonABackJson")
    public TableDataInfo listSonABackJson(@RequestParam("workFormNo") String workFormNo, @RequestParam("sdeptName") String sdeptName) {
        startPage();
        SysUser user = ShiroUtils.getSysUser();
        List<Map<String, Object>> list = gxqWfSendBackService.listSonABackJson(user.getDeptId(), workFormNo, sdeptName);
        return getDataTable(list);
    }

    /**
     * 进入下级退回全退T列表页面
     */
    @GetMapping("/listAllSonABack")
    public ModelAndView listAllSonABack() {
        return new ModelAndView(prefix + "/listAllSonABack");
    }

    /**
     * 加载下级退回全退T列表数据
     */
    @PostMapping("/listAllSonABackJson")
    public TableDataInfo listAllSonABackJson(QueryConditionVo qc) {
        startPage();
        SysUser user = ShiroUtils.getSysUser();
        qc.setUserDeptId(String.valueOf(user.getDeptId()));
        if(StringUtils.isEmpty(qc.getBeginTime()) && StringUtils.isEmpty(qc.getEndTime())) {
            //默认查询前40天
            qc.setTimeDefault("DATEADD(day,-40,convert(datetime,convert(varchar(10),getdate(),120)))");
        }
        if(StringUtils.isNotEmpty(qc.getBeginTime())) {
            qc.setBeginTime(qc.getBeginTime()+" 00:00:00.000");
        }
        if(StringUtils.isNotEmpty(qc.getEndTime())) {
            qc.setEndTime(qc.getEndTime()+" 23:59:59.999");
        }
        List<Map<String, Object>> list = gxqWfSendBackService.listAllSonABackJson(qc);
        return getDataTable(list);
    }


    /**
     * 下级办理中T 列表页面
     *
     * @return
     */
    @GetMapping("/listSonWait")
    public ModelAndView listSonWait() {
        return new ModelAndView(prefix + "/listSonWait");
    }

    /**
     * 下级办理中T 列表数据
     *
     * @param
     * @return
     */
    @PostMapping("/listSonWaitJson")
    public TableDataInfo listSonWaitJson(QueryConditionVo qc) {
        startPage();
        SysUser user = ShiroUtils.getSysUser();
        qc.setUserDeptId(String.valueOf(user.getDeptId()));
        List<Map<String, Object>> list;
        if (IS_GAOXIN()){
            list = gxqWfSendBackService.listSonWaitJson_gxq(qc);
        }else{
            list = gxqWfSendBackService.listSonWaitJson(qc);
        }
        return getDataTable(list);
    }

    /**
     * 下级已办毕T 未处理列表页面
     *
     * @return
     */
    @GetMapping("/listSonOverUntreated")
    public ModelAndView listSonOverUntreated() {
        return new ModelAndView(prefix + "/listSonOverUntreated");
    }

    /**
     * 下级已办毕T 未处理列表页面
     *
     * @return
     */
    @GetMapping("/listSonOverTreated")
    public ModelAndView listSonOverTreated() {
        return new ModelAndView(prefix + "/listSonOverTreated");
    }

    /**
     * 下级已办毕T 未处理列表数据
     *
     * @param
     * @return
     */
    @PostMapping("/listSonOverUntreatedJson")
    public TableDataInfo listSonOverUntreatedJson(@RequestParam("workFormNo") String workFormNo, @RequestParam("sbDeptName") String sbDeptName) {
        startPage();
        SysUser user = ShiroUtils.getSysUser();
        List<Map<String, Object>> list;
        if (IS_GAOXIN()){
            list = gxqWfSendBackService.listSonOverUntreatedJson_gxq(workFormNo, sbDeptName, user.getDeptId().toString());
        }else {
            list = gxqWfSendBackService.listSonOverUntreatedJson(workFormNo, sbDeptName, user.getDeptId().toString());
        }
        return getDataTable(list);
    }

    /**
     * 下级已办毕T 已处理列表数据
     *
     * @param
     * @return
     */
    @PostMapping("/listSonOverTreatedJson")
    public TableDataInfo listSonOverTreatedJson(@RequestParam("workFormNo") String workFormNo, @RequestParam("sbDeptName") String sbDeptName) {
        startPage();
        SysUser user = ShiroUtils.getSysUser();
        List<Map<String, Object>> list = gxqWfSendBackService.listSonOverTreatedJson(workFormNo, sbDeptName, user.getDeptId().toString());
        return getDataTable(list);
    }

    /**
     * 下级已办毕T 列表页面
     *
     * @return
     */
    @GetMapping("/sendBackChk/{pkId}")
    public ModelAndView sendBackChk(@PathVariable Integer pkId, ModelMap map) {
        SysUser user = getSysUser();
        GxqTwfSendBackEty sendBackEty = gxqWfSendBackService.getById(pkId);
        if(sendBackEty!=null){
            GxqTwfSendBackEty pSendBackEty = gxqWfSendBackService.curDeptHandleSend(sendBackEty.getWfId(), getSysUser().getDeptId().toString());
            if(pSendBackEty != null){
                map.put("pSendBackEty",pSendBackEty);
            }
        }
        GxqTworkFormBaseEty GxqTworkFormBaseEty = gxqWorkFormBaseService.getById(sendBackEty.getWfId());
        List<Map<String, Object>> telExistTags = null;
        map.put("sendBackEty", sendBackEty);
        map.put("workFormEty", GxqTworkFormBaseEty);
        if(GxqTworkFormBaseEty!=null){
            telExistTags = tagService.selectTelExistTag(String.valueOf(GxqTworkFormBaseEty.getGetDealPk()),user.getDeptId().toString(),user.getUserId().toString());
        }
        if(telExistTags != null && telExistTags.size() > 0){
            map.put("wfTag",telExistTags);
        }
        return new ModelAndView(prefix + "/sendBackChk");
    }

    /**
     * 下级办理中 审核 数据
     *
     * @param sendBackEty
     * @param req
     * @return
     */
    @PostMapping("/sendBackChkJson")
    public AjaxResult sendBackChkJson(GxqTwfSendBackEty sendBackEty, HttpServletRequest req) {
        // 保存响应结果
        boolean flag = false;
        // 校验入参不为空
        if (Objects.nonNull(sendBackEty)) {
            String temp = "";
            // 获取审查意见
            String chkDesc = req.getParameter("opinion");
            // 获取不通过理由
            temp = req.getParameter("reason");
            if (temp.length() > 1) {
                temp = chkDesc + "（" + temp + "）";
            } else {
                temp = chkDesc;
            }
            UpdateWrapper<GxqTwfSendBackEty> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("PkId", sendBackEty.getPkId()).set("SendRemark", temp).set("BackState", sendBackEty.getBackState());
            flag = gxqWfSendBackService.update(null, updateWrapper);
            if (flag) {
                SysUser user = ShiroUtils.getSysUser();
                GxqTworkFormLogEty etyLog = new GxqTworkFormLogEty();
                etyLog.setWfId(sendBackEty.getWfId());
                etyLog.setOpDeptNo(user.getDeptId().toString());
                etyLog.setOpDeptName(user.getDeptName());
                etyLog.setOpUserNo(user.getUserNo());
                etyLog.setOpUserName(user.getUserName());
                if (sendBackEty.getBackState() == 22) {
                    temp = "不通过";
                } else {
                    temp = "通过";
                }
                temp = "审查" + sendBackEty.getSbdeptName() + "办理结果（" + temp + "）";
                etyLog.setOpAction("审查结果");
                etyLog.setOpBtnId(-1);
                etyLog.setWsDesc(temp);
                etyLog.setWsOpen(0);
                etyLog.setOpDesc(temp);
                etyLog.setEffectFlag(-1);
                gxqITworkFormLogService.save(etyLog);
            }
        }
        return toAjax(flag);
    }
    /**
     * 进入派单管理列表页面
     */
    @GetMapping("/sendBackList")
    public ModelAndView sendBackList(Integer wfId, Integer telId,Integer sbId,Integer pid, ModelMap map){
        map.put("wfId",wfId);
        map.put("telId",telId);
        map.put("sbId",sbId);
        map.put("pid",pid);
        return new ModelAndView(prefix + "/sendBackList");
    }

    /**
     * 加载派单管理列表数据
     */
    @PostMapping("/sendBackListJson")
    public TableDataInfo sendBackListJson(GxqTwfSendBackEty sendBack){
        startPage();
        List<Map<String, Object>> list = gxqWfSendBackService.sendBackJson(sendBack,getSysUser().getDeptId());
        return getDataTable(list);
    }
    /**
     * 派单部门编辑页面
     */
    @GetMapping("/sendDeptEdit/{wfId}/{sbId}")
    public ModelAndView sendDeptEdit(@PathVariable Integer wfId, @PathVariable(required = false) Integer sbId, ModelMap map) {
        GxqTworkFormBaseEty GxqTworkFormBaseEty = gxqWorkFormBaseService.getById(wfId);
        map.put("tworkFormBase", GxqTworkFormBaseEty);
        GxqTwfSendBackEty GxqTwfSendBackEty = gxqWfSendBackService.getById(sbId);
        map.put("twfSendBack", GxqTwfSendBackEty);
        return new ModelAndView(prefix + "/sendDeptEdit");
    }


    /**
     * 拟办部门页面
     */
    @GetMapping("/sendDept/{pkId}")
    public ModelAndView sendDept(@PathVariable Integer pkId,Integer pid, ModelMap map) {
        SysUser user = ShiroUtils.getSysUser();
        GxqTworkFormBaseEty tworkFormBase = gxqWorkFormBaseService.getById(pkId);
        GxqTwfSendBackEty twfSendBack = new GxqTwfSendBackEty();
        twfSendBack.setSdeptId(user.getDeptId().toString());
        twfSendBack.setSdeptName(user.getDeptName());
        twfSendBack.setSuserNo(user.getUserNo());
        twfSendBack.setSuserName(user.getUserName());
        map.put("tworkFormBase", tworkFormBase);
        map.put("wfId", tworkFormBase.getPkId());
        map.put("getDealPk", tworkFormBase.getGetDealPk());
        map.put("sdeptName", user.getDept().getDeptShort());
        map.put("sdeptId", twfSendBack.getSdeptId());
        map.put("suserName", twfSendBack.getSuserName());
        map.put("suserNo", twfSendBack.getSuserNo());
        map.put("deptId", user.getDeptId());
        map.put("sendTime", DateUtils.getTime());
        map.put("pid", pid);
        return new ModelAndView(prefix + "/sendDept");
    }
    
    /**
     * 删除派单
     */
    @PostMapping("/removeSendBack")
    public AjaxResult removeSendBack(String... ids){
        return toAjax(gxqWfSendBackService.removeByIds(Arrays.asList(ids)));
    }

    /**
     * 撤回派单
     */
    @PostMapping("/returnBack/{id}")
    public AjaxResult returnBack(@PathVariable("id")Integer id){
        //修改电话拟派工单
        UpdateWrapper<GxqTwfSendBackEty> sbUpdateWrapper = new UpdateWrapper<>();
        sbUpdateWrapper
                .set("SendState",30)
                .eq("PkId",id);
        boolean flag = gxqWfSendBackService.update(sbUpdateWrapper);
        GxqTwfSendBackEty twfSendBack = gxqWfSendBackService.getById(id);
        commonDao.proTsubBackState(twfSendBack.getWfId(),id);
        return toAjax(flag);
    }

    /**
     * 催办工单
     * @param ids
     * @return
     */
    @PostMapping("/urgeTransact")
    public AjaxResult urgeTransact(String ids,String wfNo, String dept,int smsInform){
        if(StringUtils.isNotNull(ids) && StringUtils.isNotNull(wfNo) && StringUtils.isNotNull(dept)){
            if(ids.contains(",")){
                String[] id = ids.split(",");
                for (int i = 0; i < id.length; i++) {
                    gxqWfSendBackService.updateUrgeTransact(id[i]);
                }
            }else {
                gxqWfSendBackService.updateUrgeTransact(ids);
            }
            if(smsInform == 1){
                smsNoteService.sendSmsNote(dept,wfNo,"催办");
            }
            return success();
        }
        return error("催办失败，请重试");
    }

    /**
     * 通过并再回
     */
    @GetMapping("/passOrReply")
    public ModelAndView passOrReply(Integer sendId, Integer wfId, ModelMap map) {
        map.put("sendBackEty", gxqWfSendBackService.curDeptHandleSend(wfId,getSysUser().getDeptId().toString()));
        map.put("user", ShiroUtils.getSysUser());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        map.put("nowTime", sdf.format(DateUtils.getNowDate()));
        map.put("replyTemplate",replyTemplateService.selectTelRnByDeptOrUser(getSysUser().getDeptId().toString(), getSysUser().getUserNo()));
        List<GxqTwfSendBackEty> listSendDept = gxqWfSendBackService.listSendSubDeptByPid(sendId, getSysUser().getDeptId());
        List<GxqTwfSendBackEty> listSendDeptSon = gxqWfSendBackService.listSendDeptSon(wfId, getSysUser().getDeptId());
        if(listSendDept == null || listSendDept.size() == 0){
            listSendDept = listSendDeptSon;
        }else{
            if(listSendDept.size() != listSendDeptSon.size()){
                listSendDept = listSendDeptSon;
            }
        }
//        List<GxqTwfSendBackEty[]> sonBackList = new ArrayList<>();
//        if(!listSendDept.isEmpty()) {
//            GxqTwfSendBackEty[] sons = new GxqTwfSendBackEty[3];
//            for (int i = 0; i < listSendDept.size(); i++) {
//                if (i % 2 == 0 && i != 0) {
//                    sonBackList.add(sons);
//                    sons = new GxqTwfSendBackEty[3];
//                }
//                sons[i % 2] = listSendDept.get(i);
//                if ((i + 1) == listSendDept.size()) {
//                    sonBackList.add(sons);
//                }
//            }
//        }
        map.put("sonBackList",listSendDept);
        map.put("sendId",sendId);
        map.put("wfId",wfId);
        return new ModelAndView(prefix + "/passOrReply");
    }

    /**
     * 催办工单
     * @param ids
     * @return
     */
    @PostMapping("/supUrgeTransact")
    public AjaxResult supUrgeTransact(String ids,String wfIds,String wfNos,int smsInform){
        if(StringUtils.isNotNull(ids) && StringUtils.isNotNull(wfIds) && StringUtils.isNotNull(wfNos)){
            StringBuilder deptIds = new StringBuilder();
            StringBuilder workFormNo = new StringBuilder();
            List<GxqTwfSendBackEty> listSendDept = new ArrayList<GxqTwfSendBackEty>();
            if(ids.contains(",")){
                String[] pkId = ids.split(",");   // 派单
                String[] wfId = wfIds.split(","); // 工单
                String[] wfNo = wfNos.split(","); // 工单编号
                for (int i = 0; i < pkId.length; i++) {
                    listSendDept = gxqWfSendBackService.listSendDeptSon(Integer.parseInt(wfId[i]), getSysUser().getDeptId());
                    for (GxqTwfSendBackEty sendBackEty : listSendDept) {
                        // 未回复和未审
                        if(sendBackEty.getBackState() == 0 || sendBackEty.getBackState()==10){
                            deptIds.append(sendBackEty.getSbdeptId()).append(",");
                            workFormNo.append(wfNo[i]).append(",");
                            gxqWfSendBackService.updateUrgeTransact(String.valueOf(sendBackEty.getPkId()));
                        }
                    }
                }
            }else{
                listSendDept = gxqWfSendBackService.listSendDeptSon(Integer.parseInt(wfNos), getSysUser().getDeptId());
                for (GxqTwfSendBackEty sendBackEty : listSendDept) {
                    // 未回复和未审
                    if(sendBackEty.getBackState() == 0 || sendBackEty.getBackState()==10){
                        deptIds.append(sendBackEty.getSbdeptId()).append(",");
                        workFormNo.append(wfNos).append(",");
                        gxqWfSendBackService.updateUrgeTransact(String.valueOf(sendBackEty.getPkId()));
                    }
                }
            }
            if(smsInform == 1){
                smsNoteService.sendSmsNote(deptIds.toString(),workFormNo.toString(),"催办");
            }
            return success("催办成功");
        }
        return error("催办失败，请重试");
    }
}
